<template>
	<view class="content">
		<el-form :model="sampleInfo" ref="sampleFormRef" label-position="top">
			<!-- <el-form-item v-if="!isAdd">
				<el-row type="flex" justify="end">
					<el-button type="default" @click="editDetails">
						<Icon class="mr-5rpx" icon="ep:edit" />{{ $t(`global.edit`) }}
					</el-button>
					<el-button type="default" @click="shareLink">
						<Icon class="mr-5rpx" icon="ep:share" />{{ $t(`global.share`) }}
					</el-button>
					<el-button v-if="!isAdd" type="danger" @click="deletesample">
						<Icon class="mr-5rpx" icon="ep:delete" />{{ $t(`global.delete`) }}
					</el-button>
				</el-row>
			</el-form-item> -->
			<el-row :gutter="10">
				<el-col :span="24">
					<el-form-item :label="$t(`electronicDetail.from.sampleName`)">
						<span v-if="!isEdit && !isAdd">{{ sampleInfo.name }}</span>
						<el-input style="width: 100%" v-model="sampleInfo.name" v-else />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item :label="$t(`electronicDetail.from.receptionTime`)">
						<el-date-picker v-model="sampleInfo.operTime" :disabled="!isEdit && !isAdd" style="width: 100%"
							type="datetime" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss"
							:placeholder="$t(`global.select`)" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item :label="$t(`electronicDetail.from.validity`)">
						<el-date-picker :disabled="!isEdit && !isAdd" style="width: 100%"
							v-model="sampleInfo.effectiveTime" type="datetime" format="YYYY-MM-DD"
							value-format="YYYY-MM-DD HH:mm:ss" :placeholder="$t(`global.select`)" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item :label="$t(`electronicDetail.from.interiorRemark`)">
						<span v-if="!isEdit && !isAdd">{{ sampleInfo.memo }}</span>
						<el-input type="textarea" v-model="sampleInfo.memo" v-else />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item :label="$t(`electronicDetail.from.remark`)">
						<span v-if="!isEdit && !isAdd">{{ sampleInfo.internalMemo }}</span>
						<el-input type="textarea" v-model="sampleInfo.internalMemo" v-else />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item>
						<proList v-model="sampleInfo.list" :readonly="!isAdd && !isEdit" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-collapse v-model="activeNames" style="margin-top: 30px">
				<el-collapse-item name="1">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`electronicDetail.information.title`) }}</el-text>
					</template>
					<el-row :gutter="10">
						<el-col :span="24">
							<el-form-item :label="$t(`electronicDetail.information.name`)">
								<span v-if="!isEdit && !isAdd">{{ sampleInfo.username }}</span>
								<el-input v-model="sampleInfo.username" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`electronicDetail.information.phone`)">
								<span v-if="!isEdit && !isAdd">{{ sampleInfo.phone }}</span>
								<el-input v-model="sampleInfo.phone" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`electronicDetail.information.email`)">
								<span v-if="!isEdit && !isAdd">{{ sampleInfo.email }}</span>
								<el-input v-model="sampleInfo.email" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`electronicDetail.information.adress`)">
								<span v-if="!isEdit && !isAdd">{{ sampleInfo.address }}</span>
								<el-input v-model="sampleInfo.address" v-else />
							</el-form-item>
						</el-col>
					</el-row>
				</el-collapse-item>
				<el-collapse-item name="2">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`electronicDetail.history.title`) }}</el-text>
					</template>
					<el-table :data="viewList" :border="true">
						<el-table-column :label="$t(`electronicDetail.history.lookTime`)" prop="checkTime" />
						<el-table-column :label="$t(`electronicDetail.history.ipAdress`)" prop="ip" />
						<el-table-column :label="$t(`electronicDetail.history.lookAdress`)" prop="address" />
					</el-table>
				</el-collapse-item>
			</el-collapse>
		</el-form>
		<el-row type="flex" justify="center" class="guding">
			<el-button type="primary" @click="editDetails" v-if="!isEdit">{{ $t(`global.edit`) }}</el-button>
			<el-button type="primary" v-if="isEdit || isAdd" @click="submitForm">{{ $t(`global.verify`) }}</el-button>
			<el-button @click="cacel">{{ $t(`global.cancel`) }}</el-button>
		</el-row>

		<el-dialog v-model="shareDialog" @closed="cacelShare">
			<el-input v-model="shareLinks" />
			<el-row type="flex" justify="center" style="margin-top: 20px">
				<el-button type="primary" @click="copyLink">复制链接</el-button>
				<el-button @click="cacelShare">{{ $t(`global.cancel`) }}</el-button>
			</el-row>
		</el-dialog>

		<uni-popup ref="popup" background-color="#fff" border-radius="10px 10px 0 0">
			<uni-row class="demo-uni-row">
				<uni-col :span="24">
					<el-button type="info" :icon="Share" text @click="shareLink">&nbsp&nbsp&nbsp&nbsp{{
						$t(`global.share`)
						}}</el-button>
				</uni-col>
				<uni-col :span="24" style="margin-top: 10px;">
					<el-button type="info" :icon="Delete" text @click="deletesample">&nbsp&nbsp&nbsp&nbsp{{
						$t(`global.delete`)
					}}</el-button>
				</uni-col>
			</uni-row>
		</uni-popup>

	</view>
</template>
<script lang="ts" setup>
import { Delete, Share } from '@element-plus/icons-vue'
import { FormInstance } from "element-plus";
import proList from '@/pages/hkb/components/proList/index.vue'
import * as sampleApi from '@/service/api/hkb/electronic/index'
import { ref } from 'vue'
import type { sampleVO, ColumnVO, ViewListVO } from '../types'
import { useRouter } from 'vue-router';
import axios from 'axios';
import { createView } from "@/service/api/hkb/view";
import Storage from "@/modal/useStorage";
import { formatDate } from '@/utils/formatTime'
import i18n from '@/main'
import { Navigate } from '@/utils';
onLoad(() => {
	const electronicDetail = Storage.get('electronicDetail')
	isAdd.value = electronicDetail.isAdd
	isEdit.value = electronicDetail.isEdit
	if (isAdd.value) {
		uni.setNavigationBarTitle({
			title: i18n.global.locale === 'zh' ? '新增电子样本' : 'ADDELECTRONIC'
		})
		Storage.set('selectGoods', [])
	} else {
		uni.setNavigationBarTitle({
			title: i18n.global.locale === 'zh' ? '电子样本详情' : 'ELECTRONICDETAIL'
		});
		Storage.set('selectGoods', electronicDetail.electronic.list)
	}
	if (electronicDetail.electronic) {
		sampleInfo.value = electronicDetail.electronic
	}
})

const popup = ref()
onNavigationBarButtonTap(async (e) => {
	popup.value.open('bottom');
})


const router = useRouter()
// defineOptions({ name: 'Product' })

const showDetail = ref(false)
const showsampleDetail = ref(false)
const isAdd = ref(false) //是否新增
const isEdit = ref(false) //是否编辑
const childRef = ref()
const loading = ref(false) // 列表的加载中
const buttonLoading = ref(false) //按钮的加载
const total = ref(0) // 列表的总页数
const activeNames = ref('1')
const list = ref<sampleVO[]>([]) // 列表的数据
const viewList = ref<ViewListVO[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileDetailList = ref([]);
const accessDetail = ref(false)
const shareDialog = ref(false)
const shareLinks = ref('')
const message = useMessage() // 消息弹窗

const allCol = ref<ColumnVO[]>([
	{ label: '样本名称', prop: 'name', width: '' },
	{ label: '创建时间', prop: 'operTime', width: '200px' },
	{ label: '有效期', prop: 'effectiveTime', width: '200px' },
	{ label: '备注', prop: 'memo', width: '' },
	{ label: '内部备注', prop: 'internalMemo', width: '' },
	{ label: '样品列表', prop: 'list', width: '' },
	{ label: '姓名', prop: 'username', width: '' },
	{ label: '电话', prop: 'phone', width: '' },
	{ label: '邮箱', prop: 'email', width: '' },
	{ label: '公司地址', prop: 'address', width: '' },
	{ label: '查看历史', prop: 'hislist', width: '' },
	{ label: '创建人', prop: 'creator', width: '' }
])
const checkCol = ref<ColumnVO[]>([])
const checked = ref([])

const options = [
	{
		value: 'HTML',
		label: 'HTML',
	},
	{
		value: 'CSS',
		label: 'CSS',
	},
	{
		value: 'JavaScript',
		label: 'JavaScript',
	},
]

const queryParams = ref({
	pageNum: 1,
	pageSize: 10
}) // 查询参数

const sampleFormRef = ref<FormInstance>()
const sampleInfo = ref<sampleVO>({
	id: '',
	name: '',
	operTime: '',
	memo: '',
	internalMemo: '',
	username: '',
	phone: '',
	email: '',
	address: '',
	effectiveTime: '',
	productids: '',
	list: [],//商品列表
})
const sampleInfoInitForm = ref<sampleVO>({
	id: '',
	name: '',
	operTime: '',
	memo: '',
	internalMemo: '',
	username: '',
	phone: '',
	email: '',
	address: '',
	effectiveTime: '',
	productids: '',
	list: [],
})

const singleView = ref<ViewListVO>({
	checkTime: '',
	ip: '',
	address: '',
	viewType: '',
	sampleid: '',
})

const getList = async () => {
	const res = await sampleApi.getList(queryParams.value)
	console.log(res)
	if (res.list.length > 0) {
		list.value = res.list
		total.value = res.total
	}
}

//提交接待
const submitForm = async () => {
	let ids = []
	sampleInfo.value.list?.map(item => {
		ids.push(item.id)
	})
	sampleInfo.value.list = []//清空商品列表保留商品id
	sampleInfo.value.productids = ids.join(';')
	sampleFormRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			buttonLoading.value = true;
			if (sampleInfo.value.id) {
				await sampleApi.editSample(sampleInfo.value).finally(() => (buttonLoading.value = false));
			} else {
				console.log(sampleInfo.value)
				await sampleApi.addSample(sampleInfo.value).finally(() => (buttonLoading.value = false));
			}
			showsampleDetail.value = false;
			cacel()
		}
	})
}

/** 分享链接 **/
const shareLink = () => {
	// shareDialog.value = true
	shareLinks.value = window.location.href + '?shareId=' + productInfo.value.id
	uni.showModal({
		content: shareLinks.value,//模板中提示的内容
		confirmText: '复制内容',
		success: () => {//点击复制内容的后调函数
			//uni.setClipboardData方法就是讲内容复制到粘贴板
			uni.setClipboardData({
				data: shareLinks.value,//要被复制的内容
				success: () => {//复制成功的回调函数
					uni.showToast({//提示
						title: '复制成功'
					})
				}
			});
		}
	});
}

/** 取消分享 **/
const cacelShare = () => {
	shareDialog.value = false
}

/** 复制链接 **/
const copyLink = () => {
	navigator.clipboard.writeText(shareLinks.value);
	message.success('链接已复制到剪切板')
}

/** 记录分享访问次数 **/
const countShare = async () => {
	let id = router.currentRoute.value.query.shareId
	if (id) {
		try {
			const response = await axios.get?.('https://qifu-api.baidubce.com/ip/local/geo/v1/district');
			singleView.value.checkTime = new Date()
			singleView.value.ip = response.data.ip
			singleView.value.address = response.data.data.prov + response.data.data.city + response.data.data.district
			singleView.value.viewType = '1'
			singleView.value.sampleid = id
		} catch (error) {
			console.error('请求错误', error);
			return null;
		}
		console.log(singleView)
		const res = await createView(singleView.value)
		let sharedPro = list.value.find(item => item.id === parseFloat(id))
		sampleDetails(sharedPro)
	}
}

/** 删除 **/
const deletesample = async () => {
	try {
		// 二次确认
		await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
		// 提交执行
		sampleApi.deleteSample(sampleInfo.value.id).then((res) => {
			if (res) {
				message.success('删除成功')
			} else {
				message.warning('删除失败')
			}
		}).finally(() => (cacel(), getList()))
	} catch (error) { }
}

//详情
const sampleDetails = (row) => {
	isEdit.value = false
	viewList.value = row?.hislist
	viewList.value.map(item => {
		item.checkTime = new Date(item.checkTime).toLocaleString()
		return item
	})
	showsampleDetail.value = true
	sampleInfo.value = row
}

const editDetails = () => {
	isEdit.value = true
	isAdd.value = false
}

/** 查看商品详情 **/
const proDetails = (row) => {
	isEdit.value = false
	isAdd.value = false
	showDetail.value = true
	childRef.value.initFormValue(row)
}

//显示新增
const showAdd = async () => {
	isEdit.value = false
	isAdd.value = true
	showsampleDetail.value = true
}

const showAccess = () => {
	accessDetail.value = true
}

//关闭弹窗
const cacel = () => {
	Navigate.to('/pages/hkb/electronic/electronic')
}

/** 激活时 */
onActivated(() => {
	getList()
	countShare()
})

/** 初始化 **/
onMounted(async () => {
	await getList()
	await countShare()
	checkCol.value = JSON.parse(JSON.stringify(allCol.value))
	checked.value = JSON.parse(JSON.stringify(allCol.value.map((item) => item.label)))
})

</script>
<style lang="scss" scoped>
.content {
	background: #fff;
	padding: 0 20rpx;

	.title {
		font-size: 40rpx;
		margin: 20rpx 10rpx;
	}
}

.tableOp {
	margin-bottom: 10px;
}

.tag {
	margin: 5px 5px;
}

.form_sub_title {
	font-weight: 600;
}

::v-deep .line_flex .el-upload {
	display: flex;
}

.guding {
	position: fixed;
	bottom: 10px;
	right: 50px;
}

::v-deep .uni-popup__wrapper {
	padding: 10px;
}
</style>
